package com.nebula.service.impl;

import com.nebula.entity.Icon;
import com.nebula.common.PageResult;
import com.nebula.common.Result;
import com.nebula.dao.IIconDao;
import com.nebula.dao.impl.IconDaoImpl;
import com.nebula.service.IIconService;
import com.nebula.util.DateTimeUtil;
import com.nebula.vo.IconVo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 * @create 2019-01-17 11:07
 */
public class IconServiceImpl implements IIconService {
    private IIconDao iIconDao = new IconDaoImpl();

    @Override
    public Result findAll() {
        List<Icon> all = iIconDao.findAll();
        List<IconVo> iconVos = new ArrayList<>();
        for (Icon icon : all) {
            IconVo iconVo = assembleIcon(icon);
            iconVos.add(iconVo);
        }
        return Result.createBySuccess(iconVos);
    }

    @Override
    public PageResult<IconVo> findByPage(int currPage, int pageSize) {
        List<Icon> icons = iIconDao.findByPage(currPage, pageSize);
        Integer totalCount = iIconDao.selectCount("icon");
        List<IconVo> iconVos = new ArrayList<>();
        for (Icon icon : icons) {
            IconVo iconVo = assembleIcon(icon);
            iconVos.add(iconVo);
        }
        PageResult<IconVo> pageResult = new PageResult<>();
        pageResult.setList(iconVos);
        pageResult.setCurrPage(currPage);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalCount(totalCount);
        Double totalPage = Math.ceil(totalCount.doubleValue() / pageSize);
        pageResult.setTotalPage(totalPage.intValue());
        return pageResult;
    }

    @Override
    public void insert(Icon icon) {
        iIconDao.save(icon);
    }

    @Override
    public IconVo findById(String id) {
        Icon icon = iIconDao.findById(id);
        IconVo iconVo = assembleIcon(icon);
        return iconVo;
    }

    @Override
    public void update(Icon icon) {
        iIconDao.update(icon);
    }

    @Override
    public void delete(int id) {
        iIconDao.delete(id);
    }

    private IconVo assembleIcon(Icon icon) {
        IconVo iconVo = new IconVo();
        iconVo.setId(icon.getId());
        iconVo.setIcon(icon.getIcon());
        iconVo.setInstructions(icon.getInstructions());
        iconVo.setUser(icon.getUser());
        iconVo.setRole(icon.getRole());
        iconVo.setCreatedTime(DateTimeUtil.dateToStr(icon.getCreatedTime()));
        iconVo.setUpdatedTime(DateTimeUtil.dateToStr(icon.getUpdatedTime()));

        return iconVo;
    }
}
